<template>
  <div class="app-container inden-manage">
    <div>
      <avue-form
        :option="option"
        v-model="queryParams"
        ref="searchForm"
        v-show="showSearch"
        @keydown.enter="getList"
      >
        <template #menu-form>
          <el-button icon="Search" type="primary" @click="getList" class="m-l-3"
            >查询</el-button
          >
          <el-button icon="Refresh" @click="handleEmpty(searchForm)"
            >重置</el-button
          >
          <el-button icon="Filter" type="primary" @click="handleSearch" link
            >高级查询</el-button
          >
        </template>
      </avue-form>

      <el-drawer
        v-model="searchDrawer"
        title="高级检索"
        :show-close="false"
        size="40%"
      >
        <template #header="{ close, titleId, titleClass }">
          <h4 :id="titleId" :class="titleClass">高级检索</h4>
          <el-button
            class="search-drawer-retract"
            icon="ArrowRight"
            type="danger"
            @click="close"
            link
          >
            收起
          </el-button>
        </template>
        <avue-form
          :option="searchOption"
          v-model="queryParams"
          ref="seniorSearchForm"
          @keydown.enter="getList"
        >
          <template #projectId>
            <el-select
              v-model="queryParams.projectId"
              placeholder="请选择关联项目"
              class="w-full"
              suffix-icon="Search"
              remote-show-suffix
              :suffix-transition="false"
              filterable
              remote
              clearable
              :remote-method="queryProject"
              :loading="loadingSelect"
            >
              <el-option
                v-for="item in projectOptions"
                :key="item.projectId"
                :label="item.proName"
                :value="item.projectId"
              >
                <div>
                  <span>{{ item.proName }}</span>
                </div>
              </el-option>
            </el-select>
          </template>
          <template #contractId>
            <el-select
              v-model="queryParams.contractId"
              placeholder="请选择关联合同"
              class="w-full"
              suffix-icon="Search"
              remote-show-suffix
              :suffix-transition="false"
              filterable
              remote
              clearable
              :remote-method="queryContract"
              :loading="loadingSelect"
            >
              <el-option
                v-for="item in contractOptions"
                :key="item.rcId"
                :label="item.contractName"
                :value="item.rcId"
              >
                <div>
                  <span>{{ item.contractName }}</span>
                </div>
              </el-option>
            </el-select>
          </template>
          <template #menu-form>
            <div class="text-center">
              <el-button icon="Search" type="primary" @click="getList"
                >查询</el-button
              >
              <el-button icon="Refresh" @click="handleEmpty(searchForm)"
                >重置</el-button
              >
            </div>
          </template>
        </avue-form>
      </el-drawer>

      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button type="primary" icon="Plus" @click="handleAdd"
            >新增</el-button
          >
        </el-col>
        <!-- <el-col :span="1.5">
          <el-button type="info" plain icon="Download" @click="handleDownload"
            >导出数据</el-button
          >
        </el-col> -->
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="EditPen"
            @click="handleUpdate"
            :disabled="disUpdate"
            >编辑订单</el-button
          >
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="primary"
            icon="RemoveFilled"
            plain
            @click="handleStop"
            :disabled="disUpdate"
            >关闭订单</el-button
          >
        </el-col>
        <!-- <right-toolbar
          @queryTable="getList"
          v-model:showSearch="showSearch"
        ></right-toolbar> -->
      </el-row>

      <el-table
        v-loading="loading"
        :data="tableList"
        row-key="id"
        stripe
        @selection-change="handleSelectionChange"
        @row-dblclick="
          row => {
            goTo('/source/sourceModules/innerOrderDetails', {
              innerOrderId: row.id
            })
          }
        "
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column
          prop="number"
          label="订单编号"
          width="200"
          align="center"
        >
          <!-- <template #default="scope">
            <el-link
              type="primary"
              :underline="false"
              @click="
                goTo('/source/sourceModules/innerOrderDetails', {
                  innerOrderId: scope.row.id
                })
              "
              >{{ scope.row.number }}</el-link
            >
          </template> -->
        </el-table-column>
        <el-table-column prop="title" label="订单标题" width="230">
        </el-table-column>
        <!-- <el-table-column prop="businessType" label="业务板块" width="130">
          <template #default="scope">
            <dict-drop
              :options="order_business_type"
              :value="scope.row.businessType"
            ></dict-drop>
          </template>
        </el-table-column> -->
        <el-table-column prop="supplierName" label="供应商" width="200">
          <!-- <template #default="scope">
            <el-link
              v-if="scope.row.customerType == 'customer'"
              type="primary"
              :underline="false"
              @click="
                goTo('/source/sourceModules/supplierDetails', {
                  supplierId: scope.row.supplierId
                })
              "
              >{{ scope.row.supplierName }}</el-link
            >
            <el-link
              v-else-if="scope.row.customerType == 'cusLink'"
              type="primary"
              :underline="false"
              @click="
                goTo('/customerManage/contactsModules/contactsDetails', {
                  contactsId: scope.row.customerId
                })
              "
              >{{ scope.row.customerName }}</el-link
            >
          </template> -->
        </el-table-column>
        <el-table-column prop="status" label="状态" width="130">
          <template #default="scope">
            <div>
              <dict-drop :options="order_status" :value="scope.row.status" />
              <span
                class="text-12px text-#999999"
                v-if="scope.row.approvalStatus"
                >({{ scope.row.approvalStatus }})</span
              >
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="price" label="订单总金额" width="160">
          <template #default="scope">
            <span v-if="scope.row.price">¥{{ scope.row.price }}</span
            ><span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column prop="repaymentPrice" label="已回款金额" width="160">
          <template #default="scope">
            <span v-if="scope.row.repaymentPrice"
              >¥{{ scope.row.repaymentPrice }}</span
            ><span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column prop="invoicePrice" label="已开票金额" width="160">
          <template #default="scope">
            <span v-if="scope.row.invoicePrice"
              >¥{{ scope.row.invoicePrice }}</span
            ><span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          align="center"
          class-name="small-padding"
          min-width="90"
        >
          <template #default="scope">
            <el-button
              plain
              type="primary"
              icon="CircleCheckFilled"
              size="small"
              class="px-11px"
              @click="handleContinue(scope.row)"
              >跟进</el-button
            >
            <!-- <el-button
              link
              type="primary"
              icon="RemoveFilled"
              size="small"
              class="px-1"
              @click="
                goTo('/financial/repaymentDetails', {
                  salesOrderId: scope.row.id
                })
              "
              >回款</el-button
            > -->
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total > 0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
      />

      <!-- 跟进弹窗 -->
      <FollowUp
        :dialogParam="followUpParam"
        @ok="saveFn"
        @close="followUpParam.isVisible = false"
      ></FollowUp>

      <!-- 关闭订单弹窗 -->
      <el-dialog
        :title="stopDialog.title"
        v-model="stopDialog.open"
        width="40%"
        :close-on-click-modal="false"
      >
        <el-form
          ref="formRules"
          :model="formStopData"
          :rules="formStopRules"
          label-width="120px"
          status-icon
        >
          <el-row>
            <el-col :span="24">
              <el-form-item label="关闭原因" prop="stopReason">
                <el-input
                  v-model="formStopData.stopReason"
                  type="textarea"
                  :rows="3"
                  placeholder="请输入关闭原因"
                  maxlength="300"
                  show-word-limit
                />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="stopDialog.open = false">取 消</el-button>
            <el-button type="primary" @click="handleStopSubmit">保存</el-button>
          </span></template
        >
      </el-dialog>
    </div>
  </div>
</template>
<script setup name="InnerOrder">
import { reactive, toRefs, toRaw } from 'vue'
import { useRouter } from 'vue-router'
import {
  order_status, //订单状态
  invoice_status, //发票状态
  order_price, //订单金额
  bidding_unit, //内部单位
  companyOption, //所属公司
  loadingSelect, //加载loading
  projectOptions, //项目数据
  queryProject, //检索项目
  contractOptions, //合同数据
  queryContract //检索合同数据
} from '@/hooks/dict/order'
import { listInnerOrder, stopInnerOrder } from '@/api/indentManage/indent'
import FollowUp from '@/businessComponents/FollowUp'
const router = useRouter()
const { proxy } = getCurrentInstance()

const data = reactive({
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    number: undefined,
    status: undefined,
    receiptsDates: undefined,
    bizType: undefined,
    source: undefined,
    customerId: undefined,
    price: undefined,
    projectId: undefined,
    invoiceStatus: undefined,
    contractId: undefined,
    deptId: undefined,
    businessType: undefined
  },
  ids: [],
  selectArr: [],
  total: 0,
  option: {
    labelWidth: '10',
    menuSpan: 6,
    submitBtn: false,
    menuPosition: 'left',
    // gutter: 30,
    emptyBtn: false,
    column: [
      {
        prop: 'number',
        span: 3,
        placeholder: '订单号',
        type: 'input'
      },
      {
        // label: '性别',
        span: 3,
        prop: 'status',
        placeholder: '状态',
        type: 'select',
        dicData: order_status
      },
      // {
      //   prop: 'receiptsDates',
      //   type: 'daterange',
      //   span: 3,
      //   format: 'YYYY-MM-DD',
      //   valueFormat: 'YYYY-MM-DD',
      //   startPlaceholder: '单据开始时间',
      //   endPlaceholder: '单据结束时间'
      // },
      {
        prop: 'deptId',
        span: 3,
        placeholder: '所属公司',
        type: 'tree',
        defaultExpandAll: true,
        props: {
          value: 'id', //   value: 'deptId',
          label: 'label' //   label: 'deptName'
        },
        dicData: companyOption
      }
      // {
      //   // label: '性别',
      //   span: 3,
      //   prop: 'businessType',
      //   placeholder: '业务板块',
      //   type: 'tree',
      //   dicData: businessTypeOption
      // }
    ]
  },
  searchOption: {
    submitBtn: false,
    emptyBtn: false,
    menuPosition: 'left',
    column: [
      {
        label: '订单查询',
        prop: 'number',
        span: 12,
        placeholder: '订单号',
        type: 'input'
      },
      {
        label: '状态',
        span: 12,
        prop: 'status',
        placeholder: '状态',
        type: 'select',
        dicData: order_status
      },
      // {
      //   label: '单据时间',
      //   prop: 'receiptsDates',
      //   type: 'daterange',
      //   span: 12,
      //   format: 'YYYY-MM-DD',
      //   valueFormat: 'YYYY-MM-DD',
      //   startPlaceholder: '单据开始时间',
      //   endPlaceholder: '单据结束时间'
      // },
      // {
      //   label: '业务类型',
      //   span: 12,
      //   prop: 'bizType',
      //   placeholder: '业务类型',
      //   type: 'select',
      //   dicData: order_biz_type
      // },
      // {
      //   label: '付款时间',
      //   prop: 'payDates',
      //   type: 'daterange',
      //   span: 12,
      //   format: 'YYYY-MM-DD',
      //   valueFormat: 'YYYY-MM-DD',
      //   startPlaceholder: '付款开始时间',
      //   endPlaceholder: '付款结束时间'
      // },
      // {
      //   label: '订单来源',
      //   span: 12,
      //   prop: 'source',
      //   placeholder: '订单来源',
      //   type: 'select',
      //   dicData: order_source
      // },
      {
        label: '内部单位',
        prop: 'customerId',
        span: 12,
        placeholder: '内部单位',
        type: 'tree',
        defaultExpandAll: true,
        props: {
          value: 'id', //   value: 'deptId',
          label: 'label' //   label: 'deptName'
        },
        dicData: bidding_unit
      },
      // {
      //   label: '客户名称',
      //   span: 12,
      //   prop: 'customerId',
      //   placeholder: '客户名称'
      // },
      {
        label: '订单金额',
        span: 12,
        prop: 'price',
        placeholder: '订单金额',
        type: 'select',
        dicData: order_price
      },
      {
        label: '关联项目',
        span: 12,
        prop: 'projectId',
        placeholder: '关联项目'
      },
      {
        label: '发票状态',
        span: 12,
        prop: 'invoiceStatus',
        placeholder: '发票状态',
        type: 'radio',
        dicData: invoice_status
      },
      // {
      //   label: '关联合同',
      //   span: 12,
      //   prop: 'contractId',
      //   placeholder: '关联合同'
      // },

      {
        label: '所属公司',
        prop: 'deptId',
        span: 12,
        placeholder: '所属公司',
        defaultExpandAll: true,
        type: 'tree',
        props: {
          value: 'id', //   value: 'deptId',
          label: 'label' //   label: 'deptName'
        },
        dicData: companyOption
      }
      // {
      //   label: '业务板块',
      //   span: 12,
      //   prop: 'businessType',
      //   placeholder: '业务板块',
      //   type: 'tree',
      //   dicData: businessTypeOption
      // }
    ]
  },
  showSearch: true,
  searchDrawer: false /* 高级检索框 */,
  disUpdate: true /* 编辑按钮是否可编辑 */,
  disDelete: true /* 关闭按钮是否可编辑 */,
  loading: false,
  tableList: [],
  followUpParam: {}, // 跟进弹窗配置
  stopDialog: {
    title: '关闭订单',
    open: false
  },
  formStopData: {
    id: '',
    status: '',
    stopReason: undefined
  }, //关闭订单数据
  formStopRules: {
    stopReason: [
      {
        required: true,
        message: '请输入关闭原因',
        trigger: 'blur'
      }
    ]
  } //关闭订单效验
})
const {
  queryParams,
  ids,
  selectArr,
  total,
  option,
  searchOption,
  showSearch,
  searchDrawer,
  disUpdate,
  disDelete,
  loading,
  tableList,
  followUpParam,
  stopDialog,
  formStopData,
  formStopRules
} = toRefs(data)

// 初始化
async function init() {
  // 归属部门
  getList()
}
// 提交
function handleSubmit() {
  console.log('提交--》', queryParams.value)
}
// 重置
function handleEmpty(formEl) {
  console.log('queryParams.value1==>', toRaw(queryParams.value))
  proxy.resetForm('searchForm')
  proxy.resetForm('seniorSearchForm')
  // proxy.$refs.searchForm.resetForm()
  getList()
}
// 高级检索
function handleSearch() {
  searchDrawer.value = true
}

// 获取数据列表
function getList() {
  loading.value = true
  console.log('queryParams.value2==>', queryParams.value)
  listInnerOrder(queryParams.value).then(res => {
    loading.value = false
    tableList.value = res.rows
    total.value = res.total
    console.log(' tableList.value==>', tableList.value)
  })
  console.log('获取数据')
}
/** 多选框选中数据 */
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  selectArr.value = selection
  disUpdate.value = selection.length != 1
  disDelete.value = !selection.length
}
function goTo(url, data) {
  router.push({ path: url, query: data })
}
function handleAdd() {
  goTo('/source/sourceModules/innerOrderForm', {})
}
function handleDownload() {}
function handleUpdate() {
  goTo('/source/sourceModules/editInnerOrder', {
    innerOrderId: ids.value[0]
  })
}

//打开跟进弹窗
function handleContinue(row) {
  console.log('跟进==》', followUpParam.value)
  /***订单模块 */
  console.log('row==>', row)
  followUpParam.value.isVisible = true
  followUpParam.value.tableName = 'ord_inner_order'
  followUpParam.value.businessId = row.id
  followUpParam.value.customer = row.customerName
  followUpParam.value.orderName = row.title
}

// 确认跟进
function saveFn() {}
// 关闭订单
function handleStop() {
  proxy.resetForm('formRules')
  stopDialog.value.open = true
  formStopData.value.id = ids.value[0]
  formStopData.value.status = '4'
}
// 保存关闭订单
function handleStopSubmit() {
  proxy.$refs.formRules.validate((valid, msg) => {
    if (valid) {
      stopInnerOrder(formStopData.value).then(res => {
        proxy.$modal.msgSuccess('关闭成功')
        stopDialog.value.open = false
        getList()
      })
    }
  })
}

init()
</script>
<style scoped>
.search-drawer-retract {
  color: #999999;
}
</style>
